package cn.iocoder.yudao.module.system.controller.admin.conversation;

import cn.iocoder.yudao.module.system.controller.admin.conversation.vo.ChatConversationPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.conversation.vo.ChatConversationRespVO;
import cn.iocoder.yudao.module.system.controller.admin.conversation.vo.ChatConversationSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.chatconversation.ChatConversationDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.UserAssetsDO;
import cn.iocoder.yudao.module.system.service.chatconversation.ChatConversationService;
import cn.iocoder.yudao.module.system.service.user.UserAssetsService;
import com.baidubce.appbuilder.base.exception.AppBuilderServerException;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import reactor.core.publisher.Flux;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;
import static cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils.getLoginUserId;


@Tag(name = "管理后台 - AI 聊天对话")
@RestController
@RequestMapping("/system/ai/chat-conversation")
@Validated
public class ChatConversationController {

    @Resource
    private ChatConversationService chatConversationService;

    @Resource
    private UserAssetsService userAssetsService;

    @PostMapping("/create")
    @Operation(summary = "创建AI 聊天对话")
    @PermitAll
    public Flux<CommonResult<ChatConversationRespVO>> createChatConversation(@RequestBody ChatConversationSaveReqVO createReqVO) throws IOException, AppBuilderServerException {
        return chatConversationService.createChatConversation(createReqVO);
    }

    @PutMapping("/update")
    @Operation(summary = "更新AI 聊天对话")
    @PermitAll
    public CommonResult<Boolean> updateChatConversation(@Valid @RequestBody ChatConversationSaveReqVO updateReqVO) {
        chatConversationService.updateChatConversation(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除AI 聊天对话")
    @Parameter(name = "id", description = "编号", required = true)
    @PermitAll
    public CommonResult<Boolean> deleteChatConversation(@RequestParam("id") Long id) {
        chatConversationService.deleteChatConversation(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得AI 聊天对话")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PermitAll
    public CommonResult<ChatConversationRespVO> getChatConversation(@RequestParam("id") Long id) {
        ChatConversationDO chatConversation = chatConversationService.getChatConversation(id);
        return success(BeanUtils.toBean(chatConversation, ChatConversationRespVO.class));
    }

    @GetMapping("/quota")
    @Operation(summary = "获得AI 聊天对话剩余次数")
    @PermitAll
    public CommonResult<Integer> quota() {
        Long loginUserId = getLoginUserId();
        if (loginUserId == null) {
            return error(404,"未查询到用户信息，请重新登录");
        }else {
            UserAssetsDO userAssetsDO = userAssetsService.getUserAssetsByUserId(loginUserId);
            return success(userAssetsDO.getAskLeftCount());
        }

    }

    @GetMapping("/page")
    @Operation(summary = "获得AI 聊天对话分页")
    @PermitAll
    public CommonResult<PageResult<ChatConversationRespVO>> getChatConversationPage(@Valid ChatConversationPageReqVO pageReqVO) {
        Long userId = getLoginUserId();
        if (userId != null) {
            pageReqVO.setUserId(userId);
        }else {
            return error(404,"未查询到用户信息，请重新登录");
        }

        PageResult<ChatConversationDO> pageResult = chatConversationService.getChatConversationPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, ChatConversationRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出AI 聊天对话 Excel")
    @PermitAll
    @ApiAccessLog(operateType = EXPORT)
    public void exportChatConversationExcel(@Valid ChatConversationPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ChatConversationDO> list = chatConversationService.getChatConversationPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "AI 聊天对话.xls", "数据", ChatConversationRespVO.class,
                        BeanUtils.toBean(list, ChatConversationRespVO.class));
    }

}